import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/entities/user.entity';
import { VideoHistory } from 'src/entities/video-history.entity';
import { Video } from 'src/entities/video.entity';
import { Repository } from 'typeorm';
import { RecommendationService } from '../recommendation/recommendation.service';

@Injectable()
export class VideoHistoryService {
  constructor(
    @InjectRepository(VideoHistory)
    private videoHistoryRepository: Repository<VideoHistory>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    private readonly recommendationService: RecommendationService,
  ) {}

  // 新增浏览记录
  async create(userId: number, videoId: number): Promise<VideoHistory> {
    // 查找该用户是否已有该视频的浏览记录
    const existingHistory = await this.videoHistoryRepository.findOne({
      where: {
        user: { id: userId },
        video: { video_id: Number(videoId) },
      },
    });

    // 如果存在旧的浏览记录，删除它
    if (existingHistory) {
      await this.videoHistoryRepository.remove(existingHistory);
    }

    // 创建新的浏览记录
    const history = new VideoHistory();

    const user = await this.userRepository.findOne({
      where: { id: userId },
    });
    if (!user) {
      throw new Error('用户不存在');
    }

    const video = await this.videoRepository.findOne({
      where: { video_id: Number(videoId) },
    });
    if (!video) {
      throw new Error('视频不存在');
    }

    history.user = user;
    history.video = video;

    // 保存完成后，更新用户的推荐缓存
    await this.recommendationService.invalidateRecommendationCache(userId);

    return await this.videoHistoryRepository.save(history);
  }

  // 获取用户浏览行为
  async getPaginatedHistory(
    userId: number,
    page: number = 1,
    limit: number = 10,
  ): Promise<{ data: VideoHistory[]; total: number }> {
    const [results, total] = await this.videoHistoryRepository.findAndCount({
      where: { user: { id: userId } },
      relations: ['video', 'video.user'], // 关联视频及视频作者
      order: { createdAt: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });

    return { data: results, total };
  }

  // 查询用户最近的浏览记录（按时间倒序）
  async getUserHistory(userId: number, limit: number = 20) {
    return this.videoHistoryRepository.find({
      where: { user: { id: userId } },
      relations: ['video'],
      order: { createdAt: 'DESC' },
      take: limit,
    });
  }

  // 清理超过6个月的旧记录
  async cleanupOldRecords(): Promise<void> {
    const sixMonthsAgo = new Date();
    sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
    await this.videoHistoryRepository
      .createQueryBuilder()
      .delete()
      .where('createdAt < :sixMonthsAgo', { sixMonthsAgo })
      .execute();
  }

  async findOneByIdAndUser(
    id: number,
    userId: number,
  ): Promise<VideoHistory | null> {
    return this.videoHistoryRepository.findOne({
      where: { id, user: { id: userId } },
    });
  }

  async deleteById(id: number): Promise<void> {
    await this.videoHistoryRepository.delete(id);
  }

  // 清空用户所有浏览记录
  async clearUserHistory(userId: number): Promise<void> {
    await this.videoHistoryRepository
      .createQueryBuilder()
      .delete()
      .where('user_id = :userId', { userId })
      .execute();
  }
}
